﻿using MySql.Data.Types;
using MySqlX.XDevAPI.Relational;
using System;
using System.Collections.Generic;
using System.Text;

public class NetHandler_Login : GameServerMessageHandler
{
    public const string Login_Key = "Login";

    public static object baton = new object();

    public static NetHandler_Login NewHandler()
    {
        return new NetHandler_Login();
    }

    protected override ISerialize NewData() => new LoginRequestData();

    public override void _Execute(TCPClient client, ISerialize _data)
    {
        LoginRequestData requestData = _data as LoginRequestData;

        GameDebug.Log($"用户登入:{requestData.uuid}  isRobot:{requestData.isRobot}");

        double curTime = CommonFunctions.GetTimeStampSeconds();

        LoginResponseData response = new LoginResponseData();

        //维护判断
        if (Game.instance.data.maintainData != null)
        { 
            if (Game.instance.data.maintainData.maintainEndTime > curTime)
            {
                string clientIp = Game.GetIpWithIpAddress(client.ipEndPoint.Address);
                if (Game.instance.data.whiteListData != null
                    && Game.instance.data.whiteListData.whiteList.Contains(clientIp))
                {
                    GameDebug.Log($"白名单:{clientIp}跳过维护");
                }
                else
                {
                    response.code = -3;
                    response.err = "服务器维护中，无法登陆";

                    byte[] data = response.Write();
                    this.SendResponse(client, Login_Key, this.m_MessageReceived.seq, data);
                    return;
                }
            }
            else
            {
                Game.instance.data.maintainData = null;
            }
        }

        //版本判断
       // if(requestData.appVersion < )

        User user = null;

        double loginTime = curTime;
        double lastOfflineTime = 0;
    
        //是否是注册用户
        device existDevice = FindRegisterUser(requestData.uuid);

        if (existDevice != null)
        {
            ///已注册用户
            GameDebug.Log($"已注册用户:{existDevice.id}  username:{existDevice.uuid}");

            if (existDevice.password.Trim() != requestData.password.Trim())
            {
                response.code = -2;
                response.err = "密码不正确";
            }
            else
            {
                response.code = 0;

                users userTable = UserServer.FindInUserTable(existDevice.id);
                if (userTable != null)
                {
                    lastOfflineTime = userTable.last_offline_time;

                    string DBUser = users.GetUserDatabaseWithDeviceId(existDevice.id);

                    //texture[] textureTable = UserServer.FindInTextureTable(existDevice.id);
                    //Tex icon = requestData.needReturnIcon? TextureSaver.LoadUserTexture(existDevice.id, 1) : null;
                    //Tex tex1 = requestData.needReturnTex1? TextureSaver.LoadUserTexture(existDevice.id, 2) : null;
                    //Tex tex2 = requestData.needReturnTex2? TextureSaver.LoadUserTexture(existDevice.id, 3) : null;
                    //Tex tex3 = requestData.needReturnTex3? TextureSaver.LoadUserTexture(existDevice.id, 4) : null;
                    //Tex tex4 = requestData.needReturnTex4? TextureSaver.LoadUserTexture(existDevice.id, 5) : null;
                    //Tex tex5 = requestData.needReturnTex5? TextureSaver.LoadUserTexture(existDevice.id, 6) : null;
                    //Tex tex6 = requestData.needReturnTex6? TextureSaver.LoadUserTexture(existDevice.id, 7) : null;
                    var icon = TextureSaver.GetUserTextureUrl(existDevice.id, 1);
                    var tex1 = TextureSaver.GetUserTextureUrl(existDevice.id, 2);
                    var tex2 = TextureSaver.GetUserTextureUrl(existDevice.id, 3);
                    var tex3 = TextureSaver.GetUserTextureUrl(existDevice.id, 4);
                    var tex4 = TextureSaver.GetUserTextureUrl(existDevice.id, 5);
                    var tex5 = TextureSaver.GetUserTextureUrl(existDevice.id, 6);
                    var tex6 = TextureSaver.GetUserTextureUrl(existDevice.id, 7);

                    user = ReadUserTable(DBUser, userTable,  loginTime, icon, tex1, tex2, tex3, tex4, tex5, tex6);
                }
                else
                {
                    GameDebug.LogError($"userTable == null:{existDevice.id}");

                    long  newUserId = MysqlFunction.InsertIntoTable(ServerConfig.DBShared, SqlTable.device, existDevice);
                   
                    user = RegisterUser(newUserId, requestData.isRobot);
                }
            }
        }
        else
        {
            //未注册用户
            GameDebug.Log($"未注册用户:{requestData.uuid}");
            response.code = 1;

            device newDevice = new device(requestData.loginType, requestData.uuid, requestData.langType, requestData.os, requestData.deviceModel, requestData.deviceName);
            long newUserId  = MysqlFunction.InsertIntoTable(ServerConfig.DBShared, SqlTable.device, newDevice);
            
            user = RegisterUser(newUserId, requestData.isRobot);
        }

        if(user == null)
        {
            byte[] data = response.Write();
            this.SendResponse(client, Login_Key, this.m_MessageReceived.seq, data);
            return;
        }

        //更新到内存中
        UserServer userServer = Game.instance.AddUser(requestData.uuid, client, user, loginTime, lastOfflineTime);

        response.user = user;

        this.SendResponse(client, Login_Key, this.m_MessageReceived.seq, response.Write());


        GameDebug.Log($"Login userId:{user.id}  userInfo:{user.userInfo}");

        users.UpdateLastLoginTime(user.id, loginTime);

        //if(response.code == 1)
        //{
        //    //新用戶
        //    const int addDiamond = 100;

        //    //新用户发新手礼包
        //    //GameDebug.Log($"发送新手礼包：{client.userID}");

        //    int diamond = userServer.data.AddDiamond(addDiamond);
        //    //更新数据库
        //    users.UpdateDiamond(userServer.data.id, diamond);
        //}
        //else if (response.code == 0)
        {
            GameDebug.Log($"NetHandler_Login suc");
        }
    }

    public static device FindRegisterUser(string uuid)
    {
        if (string.IsNullOrEmpty(uuid))
        {
            GameDebug.LogError("FindRegisterUser uuid == null");
            return null;
        }
        else
        {
            device existUser = UserServer.FindInDeviceTable(uuid);
            return existUser;
        }
    }
        

    User RegisterUser(long deviceId,bool isRobot)
    {
        byte is_robot =(byte)(isRobot ? 1 : 0);
        users userTable = users.DefaultValue(isRobot);// new users("Guest", 0, 0, defaultPet, 0, 0, 0, maxWatchHomeAdTimeOneDay, is_robot,1,new List<int> { 1 },0);

        long userTableId = users.DeviceId2UserTableId(deviceId);
        userTable.id = userTableId;

        string DBUser = users.GetUserDatabaseWithDeviceId(deviceId);

        GameDebug.LogShowy($"RegisterUser ============DBUser:{DBUser} is robot:{is_robot}  deviceId:{deviceId}");

        /*long userTableId = */MysqlFunction.InsertIntoTable(DBUser, SqlTable.users, userTable,false);

        //更新默认名字
        string nick = string.Format("Guest{0:D4}", (deviceId+5000) % 10000);
        userTable.nickname = nick;
        users.UpdateNick(deviceId, nick);

        //        List<skins> newSkins = new List<skins>();
        //        List<pets> newPets = new List<pets>();

        //        ///插入默认给予的皮肤到 skins表
        //        SkinArche[] skinArches = ConstData.Instance.skins;
        //        if (skinArches != null)
        //        {
        //            GameDebug.Log($"skinArches:{skinArches.Length}");

        //            foreach (var skin in skinArches)
        //            {
        //                if (skin.defaultHave)
        //                {
        //#if SomeLog
        //                    GameDebug.Log($"skin:{skin.name}默认给予");
        //#endif
        //                    skins skinTable = new skins(deviceId, skin.skinId);

        //                    MysqlFunction.InsertIntoTable(DBUser,SqlTable.skins, skinTable);
        //                    newSkins.Add(skinTable);
        //                }
        //            }
        //        }

        var user = ReadUserTable(DBUser, userTable, 0, null, null, null, null, null, null, null);
        return user;
    }

    public const int maxWatchHomeAdTimeOneDay = 10;

    public static User ReadUserTable(string database, users ut, double loginTime, string icon,
        string tex1, string tex2, string tex3, string tex4, string tex5, string tex6)
    {
        long deviceId = users.UserTableId2DeviceId(database, ut.id);

        var user = UserServer.ReadUserTable(database, ut, icon, tex1, tex2, tex3, tex4, tex5, tex6);

        DateTime lastTime = CommonFunctions.TimeStampSeconds2DateTime(ut.last_login_time);
        DateTime curTime = CommonFunctions.TimeStampSeconds2DateTime(loginTime);

        GameDebug.Log($"上次登录日期是：{lastTime.Day}  这次登录日期是：{curTime.Day}  tex1:{user.userInfo.tex1 != null}");

        if(curTime.Day != lastTime.Day)
        {
            user.homeAdTimesRemain = maxWatchHomeAdTimeOneDay;

            users.UpdateHomeAdTimesRemain(deviceId, maxWatchHomeAdTimeOneDay);

            int loginDay = user.AddLoginDay();

            users.UpdateLoginDay(deviceId, loginDay);

            if (loginTime < user.memberTimeEndDate)
            {
                users.UpdateFreeApplyCount(deviceId, 1);
            }
        }
        else
        {
            user.homeAdTimesRemain = ut.home_ad_remain;
        }

        return user;
    }
}

